package com.kk.filter;


import com.alibaba.fastjson.JSONObject;
import com.kk.Entry.R;
import com.kk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
/*
思路
* filter过滤器 先定义webFilter注解并写上参数urlPatterns 然后在启动类上的头上定义注解ServletComponentScan 然后把请求头和请求体强转成他的子类
* 先根据请求头获取url 那字符串url和login比较如果不是登入操作那么进行下一步判断如果是执行放行操作
* 然后根据请求头获取令牌  详细：ServletRequest.getHeader("token");
*根据获取的令牌if判断先判断是否为空在判断是否有效(调用jwt的自定义的解析方法)拿try-catch包起来如果报错那么令牌是无效的不放行，反之放行
* */
@WebFilter(urlPatterns = "/*")
public class LoginCheckedFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest ServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse ServletResponse = (HttpServletResponse) servletResponse;
        String url = ServletRequest.getRequestURL().toString();

        if (url.contains("login")) {
            filterChain.doFilter(ServletRequest, ServletResponse);
            return;
        }

        String jwt = ServletRequest.getHeader("token");

        if (jwt == null) {
            R<Object> fail = R.fail("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(fail);
            servletResponse.getWriter().write(jsonString);
            return;
        }

        try {
            Claims parsedJwt = JwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            R<Object> fail = R.fail("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(fail);
            servletResponse.getWriter().write(jsonString);
            return;
        }

        filterChain.doFilter(ServletRequest, ServletResponse);

    }
}
